package co.chuangdian.oflauncher.widgets.system;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.onekit.ASSET;
import co.chuangdian.oflauncher.R;
import uc.MyFontTextView;

/**
 * 天气fragment
 * 
 * @author msy
 * 
 */
public class WeatherWidget extends LinearLayout {

	private View continerView;
	private MyFontTextView temperatureTv;
	private TextView monthTv;
	// public BDLocationListener myListener;

	// public LocationClient mLocationClient = null;
	Activity context;

	private Handler timeHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			switch (msg.what) {
			case 1:
				String yearStr = bundle.getString("yearStr");
				monthTv.setText(yearStr + " " + getWeek());
				break;
			case 2:
				String weather = bundle.getString("weather");
				String temp = bundle.getString("temp");
				temperatureTv.setText(temp);
				meatherIv.setText(weather);
				cityTv.setText("成都");
				break;
			default:
				break;
			}
		}
	};

	public WeatherWidget(Context context) {
		super(context);
		this.context = (Activity) context;
		init();
	}


	Thread timeThread = new Thread(new Runnable() {
		@Override
		public void run() {
			try {
				while (true) {
					SimpleDateFormat yearsdf = new SimpleDateFormat("MM月dd日");
					String yearStr = yearsdf.format(new Date());
					Message msg = timeHandler.obtainMessage();
					msg.what = 1;
					Bundle b = new Bundle();
					b.putString("yearStr", yearStr);
					msg.setData(b);
					Thread.sleep(1000);
					timeHandler.sendMessageDelayed(msg, 1000);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	});

	private TextView cityTv;
	private TextView meatherIv;

	private void init() {
		continerView = View.inflate(context,R.layout.widget_weather, this);
		temperatureTv = (MyFontTextView) continerView.findViewById(R.id.temperature_tv);
		monthTv = (TextView) continerView.findViewById(R.id.month_tv);
		cityTv = (TextView) continerView.findViewById(R.id.tv_city);
		meatherIv = (TextView) continerView.findViewById(R.id.iv_weather);

		rl_weather = (RelativeLayout) continerView.findViewById(R.id.rl_weather);
		HttpUtils utils = new HttpUtils(/* location.getCity() */city, /* mLocationClient, */context) {
			@Override
			public void paseJson(String json) {

				try {
					JSONObject weatherJson = new JSONObject(json);
					JSONArray retData = weatherJson.getJSONArray("HeWeather data service 3.0");
					JSONObject jsonObj = retData.getJSONObject(0);
					JSONArray jsonArray = jsonObj.getJSONArray("daily_forecast");
					JSONObject weatherObj = jsonArray.getJSONObject(0);
					JSONObject condObj = weatherObj.getJSONObject("cond");
					String weather = condObj.getString("txt_n");// 白天天气
					JSONObject tempObj = weatherObj.getJSONObject("tmp");
					String temp = tempObj.getString("max");// 最高温度

					Message msg = timeHandler.obtainMessage();
					Bundle b = new Bundle();
					b.putString("weather", weather);
					b.putString("temp", temp);
					msg.setData(b);
					msg.what = 2;
					timeHandler.sendMessage(msg);

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

		};

		utils.loadWeather();
		timeThread.start();
		/*
		 * mLocationClient = new
		 * LocationClient(context.getApplicationContext()); // 声明LocationClient类
		 * 
		 * mLocationClient.registerLocationListener(new MyLocationListener());
		 * // 注册监听函数
		 * 
		 * LocationClientOption option = new LocationClientOption();
		 * option.setOpenGps(true);// 打开gps option.setCoorType("bd09ll");//
		 * 返回的定位结果是百度经纬度,默认值gcj02 //
		 * option.setScanSpan(5000);//设置发起定位请求的间隔时间为5000ms
		 * option.setIsNeedAddress(true);// 返回的定位结果包含地址信息
		 * option.setNeedDeviceDirect(true);// 返回的定位结果包含手机机头的方向
		 * option.setLocationMode(com.baidu.location.LocationClientOption.
		 * LocationMode.Hight_Accuracy);// 设置定位模式
		 * option.setProdName(context.getPackageName());
		 * mLocationClient.setLocOption(option); if
		 * (isInterent.hasInternet(context)) { mLocationClient.start(); } else {
		 * // Toast.makeText(context.getApplicationContext(), "网络异常，请检查网络是否连接",
		 * // Toast.LENGTH_LONG).show(); }
		 */

	}

	public String getWeek() {
		Calendar calendar = Calendar.getInstance();
		String nowWeek = String.valueOf(calendar.get(Calendar.DAY_OF_WEEK));
		String[] Weeks = context.getResources().getStringArray(R.array.weekofdate);
		return (Integer.parseInt(nowWeek) - 1 < Weeks.length) ? Weeks[Integer.parseInt(nowWeek) - 1] : null;
	}

	/*
	 * private String place;
	 * 
	 * // 定位 public class MyLocationListener implements BDLocationListener {
	 * 
	 * @Override public void onReceiveLocation(BDLocation location) { if
	 * (location == null) return; StringBuffer sb = new StringBuffer(256);
	 * sb.append("time : "); sb.append(location.getTime()); sb.append(
	 * "\nerror code : "); sb.append(location.getLocType()); sb.append(
	 * "\nlatitude : "); sb.append(location.getLatitude()); sb.append(
	 * "\nlontitude : "); sb.append(location.getLongitude()); sb.append(
	 * "\nradius : "); sb.append(location.getRadius()); if
	 * (location.getLocType() == BDLocation.TypeGpsLocation) { sb.append(
	 * "\nspeed : "); sb.append(location.getSpeed()); sb.append("\nsatellite : "
	 * ); sb.append(location.getSatelliteNumber()); } else if
	 * (location.getLocType() == BDLocation.TypeNetWorkLocation) { sb.append(
	 * "\naddr : "); sb.append(location.getAddrStr()); }
	 * 
	 * place = location.getCity(); //
	 * Toast.makeText(context.getApplicationContext(), "" + place, // 1).show();
	 * HttpUtils utils = new HttpUtils(location.getCity(), mLocationClient,
	 * context) {
	 * 
	 * @Override public void paseJson(String json) { try { JSONObject
	 * weatherJson = new JSONObject(json); JSONArray retData =
	 * weatherJson.getJSONArray("HeWeather data service 3.0"); JSONObject
	 * jsonObj = retData.getJSONObject(0); JSONArray jsonArray =
	 * jsonObj.getJSONArray("daily_forecast"); JSONObject weatherObj =
	 * jsonArray.getJSONObject(0); JSONObject condObj =
	 * weatherObj.getJSONObject("cond"); String weather =
	 * condObj.getString("txt_n");// 白天天气 JSONObject tempObj =
	 * weatherObj.getJSONObject("tmp"); String temp =
	 * tempObj.getString("max");// 最高稳定
	 * 
	 * Message msg = timeHandler.obtainMessage(); Bundle b = new Bundle();
	 * b.putString("weather", weather); b.putString("temp", temp);
	 * msg.setData(b); msg.what = 2; timeHandler.sendMessage(msg);
	 * 
	 * } catch (JSONException e) { e.printStackTrace(); } }
	 * 
	 * }; utils.loadWeather(); }
	 * 
	 * }
	 */
	String city = "成都市";
	private RelativeLayout rl_weather;

	public Bitmap getWeatherIcon(String climate) {

		String[] strs = { "晴", "晴" };
		if (climate.contains("转")) {// 天气带转字，取前面那部分
			strs = climate.split("转");
			climate = strs[0];
			if (climate.contains("到")) {// 如果转字前面那部分带到字，则取它的后部分
				strs = climate.split("到");
				climate = strs[1];
			}
		}
		return getIconRes(climate);
	}

	private Bitmap getIconRes(String climate) {
		climate = PinyinUtils.getPinyin(climate);
		String filename = "weather/" + climate + ".png";

		Bitmap weatherRes = ASSET.loadImage("weather/qing.png", false);
		if (ASSET.loadImage(filename, false) != null) {
			weatherRes = ASSET.loadImage(filename, false);
		}
		return weatherRes;
		/*
		 * if (TextUtils.isEmpty(climate)) return weatherRes; if
		 * (climate.equals("晴")) { weatherRes = R.drawable.weather_icon_sunny; }
		 * else if (climate.equals("多云")) { weatherRes =
		 * R.drawable.weather_icon_cloudy; } else if (climate.equals("阴")) {
		 * weatherRes = R.drawable.weather_icon_overcast; } else if
		 * (climate.equals("雨夹雪")) { weatherRes =
		 * R.drawable.weather_icon_rainandsnow; } else if (climate.equals("小雨"))
		 * { weatherRes = R.drawable.weather_icon_lightrain; } else if
		 * (climate.equals("中雨") || climate.equals("大雨")) { weatherRes =
		 * R.drawable.weather_icon_heavyrain; } else if (climate.equals("雷阵雨"))
		 * { weatherRes = R.drawable.weather_icon_thundershower; } else if
		 * (climate.equals("阵雨")) { weatherRes = R.drawable.weather_icon_shower;
		 * } else if (climate.equals("阵雪")) { weatherRes =
		 * R.drawable.weather_icon_snowshower; } else if (climate.equals("沙尘暴"))
		 * { weatherRes = R.drawable.weather_icon_sandstrom; } else if
		 * (climate.equals("扬沙") || climate.equals("浮尘")) { weatherRes =
		 * R.drawable.weather_icon_dust; } return weatherRes;
		 */
	}

}
